package login

import (
	"fmt"
	"pool"
	"net/http"
	"crypto/sha1"
	"encoding/json"
	_ "github.com/go-sql-driver/mysql"
)

type Response struct {
	Ret int		`json:"ret"`
	Uid int		`json:"uid"`
	Username string		`json:"username"`
}

func Handler(w http.ResponseWriter, r *http.Request) {
	r.ParseForm();

	// cookie, _ := r.Cookie("uid");

	// fmt.Println("cookie: ", cookie.Value)


	if len(r.PostForm["email"]) < 1 || len(r.PostForm["password"]) < 1 {
		// fmt.Println("No data")
		return
	}

	email := r.PostForm["email"][0]
	pwd := r.PostForm["password"][0]

	// fmt.Println("email:", email)
	// fmt.Println("pwd:", pwd)

	// 密码 sha1
	h := sha1.New()
	h.Write([]byte(pwd))
	pwd = fmt.Sprintf("%x", h.Sum(nil))

	// fmt.Println("post_data:", email, pwd)

	db := <-pool.MySQL

	stmtOut, err := db.Prepare("select uid, username, password from user_t where email = ? limit 1")
	if err != nil {
		println(err.Error())
	}
	defer stmtOut.Close()

	var uid int
	var username string
	var password string


	ret := 0

	err = stmtOut.QueryRow(email).Scan(&uid, &username, &password)
	if err != nil {
		/* 该邮箱不存在 */
		ret = 1000;
	} else {
		if pwd != password {
			/* 密码错误 */
			ret = 1001
			uid = -1;
			username = ""
		}
	}

	// fmt.Println("data:", uid, username, password)
	pool.MySQL <- db

	resD := &Response{
		Ret: ret,
		Uid: uid,
		Username: username,
	}

	resB, _ := json.Marshal(resD)
	res := string(resB)
	fmt.Fprintf(w, "%s", res)
}
